import { Button, message, Select } from "antd";
import { DeleteOutlined, PlusCircleOutlined } from "@ant-design/icons";
import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import AddOption from "./Exam/AddOption";
const SelectOptions = ({
  originalOptions = [],
  originalSelectedOptions = [],
  showDelete = false,
  showAdd = false,
  onDelete = () => {},
  onAdd = () => {},
  onChange = () => {},
}) => {
  const [open, setOpen] = useState(false);
  const [options, setOptions] = useState(originalOptions);
  const [selectedOption, setSelectedOption] = useState(originalSelectedOptions);
  return (
    <div style={{ display: "flex" }}>
      <AddOption
        open={open}
        onOk={(content) => {
          if (options.find((d) => d.value === content)) {
            message.error("选项已存在");
            return;
          }
          setOptions([
            ...options,
            { label: content, value: content, key: uuidv4() },
          ]);
          setOpen(false);
        }}
        onCancel={() => setOpen(false)}
      />
      <Select
        placeholder="请输入"
        style={{ display: "block", flex: 1 }}
        maxTagCount={"responsive"}
        mode="multiple"
        options={options}
        dropdownRender={(node) => {
          return (
            <>
              {node}
              {showDelete ? (
                <Button
                  block
                  onClick={() => {
                    console.log(selectedOption);
                    if (
                      selectedOption.find(
                        (d) => d === options[options.length - 1].value
                      )
                    ) {
                      message.error("请先取消选择");
                      return;
                    }
                    setOptions(options.slice(0, -1));
                    onDelete();
                  }}
                >
                  <DeleteOutlined />
                </Button>
              ) : null}
            </>
          );
        }}
        value={selectedOption}
        onChange={(e) => {
          setSelectedOption(e);
          onChange(e);
        }}
      ></Select>
      {showAdd ? (
        <Button
          style={{ marginLeft: "10px", width: "60px" }}
          onClick={() => {
            setOpen(true);
            onAdd();
          }}
        >
          <PlusCircleOutlined />
        </Button>
      ) : null}
    </div>
  );
};
export default SelectOptions;
